//服务端程序(pthread版本)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <ctype.h>
#include <pthread.h>

typedef struct info
{
	int cfd;
	int idx;
	pthread_t threadID;
	struct sockaddr_in client;
}INFO;

INFO thinfo[1024]; 

void init_thinfo()
{
	for(int i = 0; i < 1024; i++)
	{
		thinfo[i].cfd = -1;
	}
}

int find_info()
{
	int i;
	for(i = 0; i < 1024; ++i)
	{
		if(thinfo[i].cfd == -1)
		{
			break;
		}
	}
	if(i == 1024)
	{
		return -1;
	}
	return i;
}

void *pthread_work(INFO* info)
{
	
}

int main()
{
	//创建socket
	int lfd = socket(AF_INET, SOCK_STREAM, 0);
	if(lfd < 0)
	{
		perror("error\n");
		return -1;
	}

	//绑定
	struct sockaddr_in serv;
	bzero(&serv, sizeof(serv));
	serv.sin_family = AF_INET;
	serv.sin_port = htons(8888);
	serv.sin_addr.s_addr = htonl(INADDR_ANY); //表示使用本机任意可用ip
	int ret = bind(lfd,(struct sockaddr *) &serv, sizeof(serv));
	if(ret < 0)
	{
		perror("error\n");
	}
	
	//监听
	listen(lfd, 128);
	
	//初始化
	init_thinfo();

	int i;
	int cfd;
	socklen_t lens;
	pthread_t threadID;
	struct sockaddr_in client;
	while(1)
	{
		lens = sizeof(thinfo[i].client);
		bzero(&client, sizeof(client));
		//获得一个新的连接
		cfd = accept(lfd, (struct sockaddr *)&client, lens);
		//
		i = find_info();
		if(i = -1)
		{
			close(cfd);
			continue;
		}
		//赋值
		thinfo[i].idx = i;
		thinfo[i].cfd = cfd;
		memcpy(&thinfo[i].client, &client, sizeof(client));
		//创建子线程
		pthread_creat(thinfo[i].threadID, NULL, pthread_work, &lens);
	}
	
		return 0;
}
